import 'package:flutter/material.dart';
import 'package:tencent_cloud_chat_sdk/enum/message_elem_type.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_message.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_video_elem.dart';
import 'package:video_ducafecat_flutter_v3/common/index.dart';

import '../../index.dart';

/// 视频消息
class MsgVideoElemWidget extends StatefulWidget {
  const MsgVideoElemWidget({
    super.key,
    required this.controller,
    required this.message,
    required this.onStateChange,
  });

  /// 聊天控制器
  final ChatController controller;

  /// 视频消息
  final V2TimMessage message;

  /// 状态更新
  final Function(V2TimMessage message) onStateChange;

  @override
  State<MsgVideoElemWidget> createState() => _MsgVideoElemWidgetState();
}

class _MsgVideoElemWidgetState extends State<MsgVideoElemWidget> {
  /// 视频消息内容
  V2TimVideoElem? stateElement;

  /// 消息 id
  String? msgID;

  // 下载消息详情，离线文件，并回调更新
  downloadMessageDetailAndSave() async {
    if (msgID != null && msgID != '' && stateElement != null) {
      // 是否下载
      bool isDownload = false;

      // 拉取基本信息
      if (stateElement!.videoUrl == null || stateElement!.videoUrl == '') {
        final response =
            await IMService.to.manager.getMessageOnlineUrl(msgID: msgID!);
        if (response.data != null) {
          widget.message.videoElem = response.data!.videoElem;
          Future.delayed(const Duration(microseconds: 10), () {
            if (mounted) {
              setState(() => stateElement = response.data!.videoElem!);
            }
          });
          isDownload = true;
        }
      }

      // 下载视频、封面
      if (!PlatformUtils().isWeb) {
        // 01 下载封面
        if (stateElement!.localSnapshotUrl == null ||
            stateElement!.localSnapshotUrl == '') {
          await IMService.to.manager.downloadMessage(
            msgID: widget.message.msgID!,
            messageType: MessageElemType.V2TIM_ELEM_TYPE_VIDEO, // 消息类型
            isSnapshot: true, // 是否是视频封面
          );
          isDownload = true;
        }
        // 02 下载视频
        if (stateElement!.localVideoUrl == null ||
            stateElement!.localVideoUrl == '') {
          await IMService.to.manager.downloadMessage(
            msgID: widget.message.msgID!,
            messageType: MessageElemType.V2TIM_ELEM_TYPE_VIDEO, // 消息类型
            isSnapshot: false, // 是否是视频封面
          );
          isDownload = true;
        }
      }

      // 如果下载，回调更新
      if (isDownload == true) {
        widget.onStateChange(widget.message);
      }
    }
  }

  @override
  void initState() {
    super.initState();

    msgID = widget.message.msgID;
    stateElement = widget.message.videoElem;

    downloadMessageDetailAndSave();
  }

  // 视频预览图
  Widget _buildRreview() {
    // 预览图
    Widget img = const ImageWidget.asset(
      AssetsImages.logoPng,
      width: 100,
    );
    // 优先使用本地
    if (stateElement?.localSnapshotUrl != null &&
        stateElement?.localSnapshotUrl!.isNotEmpty == true) {
      img = ImageWidget.file(
        stateElement!.localSnapshotUrl!,
        width: 100,
      );
    }
    // 网路地址
    else if (stateElement?.snapshotUrl != null &&
        stateElement?.snapshotUrl!.isNotEmpty == true) {
      img = ImageWidget.url(
        stateElement!.snapshotUrl!,
        width: 100,
      );
    }

    return img;
  }

  // 主视图
  Widget _buildView(BuildContext context) {
    // 为空，占位
    if (stateElement == null ||
        stateElement!.snapshotUrl == null ||
        stateElement!.snapshotUrl?.isEmpty == true) {
      return const SizedBox.shrink();
    }

    var ws = <Widget>[
      // 预览图
      _buildRreview(),

      // 播放按钮
      const Icon(
        Icons.play_circle_fill,
        color: Colors.white,
        size: 40,
      ),
    ]
        .toStack(
      alignment: Alignment.center,
    )
        .onTap(() {
      Navigator.push(context, MaterialPageRoute(builder: (context) {
        return GalleryWidget(
          videoLocalPath: stateElement?.localVideoUrl,
          videoUrl: stateElement?.videoUrl,
        );
      }));
    });

    return ws;
  }

  @override
  Widget build(BuildContext context) {
    return _buildView(context);
  }
}
